#!/bin/bash

# Staging环境快速搭建脚本
# 使用方法: chmod +x staging-environment-setup.sh && ./staging-environment-setup.sh

echo "🚀 开始创建Staging环境..."

# 配置变量
SERVER_IP="47.237.10.129"
SERVER_USER="root"
STAGING_PORT="3001"
STAGING_DOMAIN="staging-api.cumrbull.com.sg"
ADMIN_STAGING_DOMAIN="staging-admin.cumrbull.com.sg"

# 1. 创建Staging环境变量文件
echo "📝 创建Staging环境配置..."
cat > backend/.env.staging << 'EOF'
# Staging数据库配置
DB_HOST=rm-t4n2um727ltmubz.mysql.singapore.rds.aliyuncs.com
DB_PORT=3306
DB_USER=cmb_staging
DB_PASSWORD=Staging2024!@#
DB_NAME=cumrbull_staging

# 服务器配置
PORT=3001
NODE_ENV=staging
APP_ENV=staging

# JWT配置
JWT_SECRET=staging-jwt-secret-key-2024-$(openssl rand -hex 16)
JWT_REFRESH_SECRET=staging-refresh-secret-2024-$(openssl rand -hex 16)
JWT_EXPIRES_IN=7d
JWT_REFRESH_EXPIRES_IN=30d

# 域名配置
API_BASE_URL=https://staging-api.cumrbull.com.sg
FRONTEND_URL=https://staging.cumrbull.com.sg
ADMIN_URL=https://staging-admin.cumrbull.com.sg

# 安全配置
ENCRYPTION_KEY=staging_encryption_key_$(openssl rand -hex 16)
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
BCRYPT_SALT_ROUNDS=12

# 文件上传配置
UPLOAD_PATH=./uploads/staging
MAX_FILE_SIZE=10485760

# 邮件配置（测试用）
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=staging@cumrbull.com.sg
EMAIL_PASS=staging-email-password
EMAIL_FROM=staging@cumrbull.com.sg

# Redis配置
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=staging-redis-password

# 日志配置
LOG_LEVEL=debug
LOG_FILE=./logs/staging.log
EOF

echo "✅ Staging环境配置文件已创建"

# 2. 创建Staging数据库初始化脚本
echo "📊 创建Staging数据库初始化脚本..."
cat > scripts/create-staging-database.sql << 'EOF'
-- 创建Staging数据库和用户
CREATE DATABASE IF NOT EXISTS cumrbull_staging CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建Staging用户
CREATE USER IF NOT EXISTS 'cmb_staging'@'%' IDENTIFIED BY 'Staging2024!@#';
GRANT ALL PRIVILEGES ON cumrbull_staging.* TO 'cmb_staging'@'%';

-- 创建只读用户
CREATE USER IF NOT EXISTS 'cmb_staging_readonly'@'%' IDENTIFIED BY 'StagingReadOnly2024!@#';
GRANT SELECT ON cumrbull_staging.* TO 'cmb_staging_readonly'@'%';

FLUSH PRIVILEGES;

-- 显示创建的用户
SELECT User, Host FROM mysql.user WHERE User LIKE 'cmb_staging%';
EOF

echo "✅ 数据库初始化脚本已创建"

# 3. 创建Staging Nginx配置
echo "🌐 创建Staging Nginx配置..."
cat > nginx-staging.conf << 'EOF'
# Staging环境Nginx配置
# 需要部署到服务器的 /etc/nginx/conf.d/staging.conf

# 上游服务器配置 - Staging
upstream cu_mr_bull_staging_api {
    server 127.0.0.1:3001 max_fails=3 fail_timeout=30s;
    keepalive 32;
}

# HTTP重定向 - Staging API域名
server {
    listen 80;
    server_name staging-api.cumrbull.com.sg;
    
    # Let's Encrypt验证
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    # 重定向到HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTP重定向 - Staging管理后台域名
server {
    listen 80;
    server_name staging-admin.cumrbull.com.sg;
    
    # Let's Encrypt验证
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    # 重定向到HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS服务器 - Staging API服务
server {
    listen 443 ssl http2;
    server_name staging-api.cumrbull.com.sg;
    
    # SSL配置
    ssl_certificate /etc/letsencrypt/live/staging-api.cumrbull.com.sg/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/staging-api.cumrbull.com.sg/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    
    # 日志
    access_log /var/log/nginx/staging-api.access.log;
    error_log /var/log/nginx/staging-api.error.log;
    
    # 健康检查
    location /health {
        proxy_pass http://cu_mr_bull_staging_api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # API路由
    location /api/ {
        proxy_pass http://cu_mr_bull_staging_api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 10s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
    
    # 根路径
    location / {
        proxy_pass http://cu_mr_bull_staging_api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# HTTPS服务器 - Staging管理后台
server {
    listen 443 ssl http2;
    server_name staging-admin.cumrbull.com.sg;
    
    # SSL配置
    ssl_certificate /etc/letsencrypt/live/staging-admin.cumrbull.com.sg/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/staging-admin.cumrbull.com.sg/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    
    # 日志
    access_log /var/log/nginx/staging-admin.access.log;
    error_log /var/log/nginx/staging-admin.error.log;
    
    # 管理后台API路由
    location /api/ {
        proxy_pass http://cu_mr_bull_staging_api/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
    
    # 静态文件服务
    location / {
        root /var/www/staging-admin;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}
EOF

echo "✅ Staging Nginx配置已创建"

# 4. 创建部署脚本
echo "🚀 创建Staging部署脚本..."
cat > deploy-staging.sh << 'EOF'
#!/bin/bash

# Staging环境部署脚本
echo "🚀 开始部署Staging环境到服务器..."

SERVER_IP="47.237.10.129"
SERVER_USER="root"

# 1. 上传配置文件
echo "📤 上传配置文件..."
scp backend/.env.staging $SERVER_USER@$SERVER_IP:/opt/cumbull/backend/
scp nginx-staging.conf $SERVER_USER@$SERVER_IP:/etc/nginx/conf.d/staging.conf

# 2. 在服务器上执行部署
echo "🔧 在服务器上执行部署..."
ssh $SERVER_USER@$SERVER_IP << 'REMOTE_SCRIPT'
# 进入后端目录
cd /opt/cumbull/backend

# 停止现有的staging进程
pm2 stop cumrbull-staging 2>/dev/null || true
pm2 delete cumrbull-staging 2>/dev/null || true

# 创建staging日志目录
mkdir -p logs
mkdir -p uploads/staging

# 启动staging服务
PORT=3001 NODE_ENV=staging pm2 start production-server.js --name "cumrbull-staging" --env-file .env.staging

# 测试Nginx配置
nginx -t
if [ $? -eq 0 ]; then
    systemctl reload nginx
    echo "✅ Nginx配置已重新加载"
else
    echo "❌ Nginx配置错误"
    exit 1
fi

# 检查服务状态
echo "📊 检查服务状态..."
pm2 status
echo "\n端口监听状态:"
netstat -tlnp | grep -E ':(3000|3001)'

# 测试健康检查
echo "\n🏥 测试健康检查..."
sleep 3
curl -s http://localhost:3001/health || echo "健康检查失败"

REMOTE_SCRIPT

echo "✅ Staging环境部署完成！"
echo "📋 后续步骤:"
echo "1. 配置DNS解析: staging-api.cumrbull.com.sg -> 47.237.10.129"
echo "2. 配置DNS解析: staging-admin.cumrbull.com.sg -> 47.237.10.129"
echo "3. 申请SSL证书: certbot --nginx -d staging-api.cumrbull.com.sg -d staging-admin.cumrbull.com.sg"
echo "4. 创建staging数据库和用户"
echo "5. 测试访问: https://staging-api.cumrbull.com.sg/health"
EOF

chmod +x deploy-staging.sh
echo "✅ Staging部署脚本已创建"

# 5. 创建数据库连接测试脚本
echo "🧪 创建数据库连接测试脚本..."
cat > test-database-connection.js << 'EOF'
// 数据库连接测试脚本
const mysql = require('mysql2/promise');
require('dotenv').config({ path: '.env.staging' });

async function testDatabaseConnection() {
    console.log('🔍 测试数据库连接...');
    console.log('配置信息:');
    console.log(`Host: ${process.env.DB_HOST}`);
    console.log(`Port: ${process.env.DB_PORT}`);
    console.log(`User: ${process.env.DB_USER}`);
    console.log(`Database: ${process.env.DB_NAME}`);
    
    try {
        const connection = await mysql.createConnection({
            host: process.env.DB_HOST,
            port: process.env.DB_PORT,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_NAME
        });
        
        console.log('✅ 数据库连接成功!');
        
        // 测试查询
        const [rows] = await connection.execute('SELECT 1 as test');
        console.log('✅ 查询测试成功:', rows);
        
        // 显示数据库信息
        const [dbInfo] = await connection.execute('SELECT DATABASE() as current_db, VERSION() as version');
        console.log('📊 数据库信息:', dbInfo[0]);
        
        await connection.end();
        console.log('✅ 连接已关闭');
        
    } catch (error) {
        console.error('❌ 数据库连接失败:', error.message);
        process.exit(1);
    }
}

testDatabaseConnection();
EOF

echo "✅ 数据库测试脚本已创建"

# 6. 显示完成信息
echo ""
echo "🎉 Staging环境配置文件创建完成！"
echo ""
echo "📁 创建的文件:"
echo "  - backend/.env.staging (Staging环境变量)"
echo "  - scripts/create-staging-database.sql (数据库初始化)"
echo "  - nginx-staging.conf (Nginx配置)"
echo "  - deploy-staging.sh (部署脚本)"
echo "  - test-database-connection.js (数据库测试)"
echo ""
echo "📋 下一步操作:"
echo "1. 在RDS中执行数据库初始化脚本"
echo "2. 配置DNS解析指向服务器"
echo "3. 运行部署脚本: ./deploy-staging.sh"
echo "4. 申请SSL证书"
echo "5. 测试Staging环境"
echo ""
echo "🧪 测试数据库连接: cd backend && node ../test-database-connection.js"
echo ""